import { Component, Host, ViewChild, ElementRef } from "@angular/core";
import { AppComponent } from "../../../../app/app.component";
import { ActivatedRoute } from "@angular/router";
import { GovernanceReportsService } from "../governanceReports.service";
import { forkJoin } from "rxjs";
import { GovernanceInsightModel, GovernancePdfType } from "../models/governanceInsight.model";
import { GovernanceMetadataModel, UpdateOperationType } from "../models/governanceMetadata.model";
import { GovernanceProfileModel } from "../models/governanceProfile.model";
import { FileUploader } from "ng2-file-upload";
import { StorageService } from "../../../shared/services/storage.service";
import { environment } from "../../../../environments/environment";
import { ToasterService } from "angular2-toaster";
import swal, { SweetAlertOptions } from "sweetalert2";
import { UtilsService } from "../../../shared/services/utils.service";
import { LrtmService, LongRunningTaskTypeEnum } from "../../../framework/lrtm/lrtm.service";
import { ColumnOptions, ColumnType } from "../../../shared/components/table/models/columnOptions.model";
import { TableButton, ButtonType } from "../../../shared/components/table/models/tableButton.model";
import { TableComponent, PaginationPositionDisplayEnum } from "../../../shared/components/table/table.component";
import { ModalComponent } from "../../../shared/components/modal/modal.component";
declare var $: any;

@Component({
    templateUrl: 'companyReport.component.html'
})
export class CompanyReportComponent {
    public name: string;
    public report: GovernanceProfileModel;
    public metadata: GovernanceMetadataModel[];
    public profile: GovernanceInsightModel;
    public businessAndFinancialProfile: GovernanceMetadataModel;
    public hasBusinessAndFinancialProfile: boolean;
    public governanceDataProfile: GovernanceMetadataModel;
    public hasGovernanceDataProfile: boolean;
    public governancePdfType: typeof GovernancePdfType = GovernancePdfType;
    public businessAndFinancialUploader: FileUploader;
    public governanceDataUploader: FileUploader;
    public insightUploader: FileUploader;
    private companyId: string;
    public hasProfile: boolean = false;
    public insights: any[];
    public insight: any;
    public count: number;
    public showInsightFile: boolean = false;
    public paginationPosition = PaginationPositionDisplayEnum.Down;

    @ViewChild('selectedBusinessAndFinancial') selectedBusinessAndFinancial: ElementRef;
    @ViewChild('selectedGovernance') selectedGovernance: ElementRef;
    @ViewChild('insightsTable') insightsTable: TableComponent;
    @ViewChild('editModal') editModal: ModalComponent;

    public columns: ColumnOptions[] = [
        new ColumnOptions('publicationDate', 'Publication date', 'col-md-2', false, ColumnType.DateTime),
        new ColumnOptions('title', 'Title', 'col-md-3', false, ColumnType.Label),
        new ColumnOptions('createdBy', 'Created By', 'col-md-3', false, ColumnType.Label),
        new ColumnOptions('action', 'Actions', 'col-md-4', false, ColumnType.Buttons)
    ];

    constructor(@Host() private rootComponent: AppComponent,
        private route: ActivatedRoute,
        private governanceService: GovernanceReportsService,
        private toasterService: ToasterService,
        private lrtmService: LrtmService) { }

    ngOnInit() {
        this.businessAndFinancialUploader = new FileUploader({});
        this.governanceDataUploader = new FileUploader({});
        this.insightUploader = new FileUploader({});
        this.route.params.subscribe(param => {
            this.name = param['name'];
            this.companyId = param['id'];
            this.loadData();
        });

        this.businessAndFinancialUploader.onAfterAddingFile = (data: any) => {
            data.withCredentials = false;
            this.businessAndFinancialUploader.setOptions(this.getUploaderOptions(data.file.name, GovernancePdfType.BusinessAndFinancialProfile));
            this.businessAndFinancialUploader.uploadAll();
        };

        this.businessAndFinancialUploader.onSuccessItem = (item: any, response: any, status: any, headers: any) => {
            this.governanceService.setGovernanceReport(this.companyId, item.file.name, GovernancePdfType.BusinessAndFinancialProfile).subscribe(_ => {
                this.toasterService.pop('success', 'Success', 'File uploaded successfully');
                this.loadData();
            });
        };        

        this.governanceDataUploader.onAfterAddingFile = (data: any) => {
            data.withCredentials = false;
            this.governanceDataUploader.setOptions(this.getUploaderOptions(data.file.name, GovernancePdfType.GovernanceDataProfile));
            this.governanceDataUploader.uploadAll();
        };

        this.governanceDataUploader.onSuccessItem = (item: any, response: any, status: any, headers: any) => {
            this.governanceService.setGovernanceReport(this.companyId, item.file.name, GovernancePdfType.GovernanceDataProfile).subscribe(_ => {
                this.toasterService.pop('success', 'Success', 'File uploaded successfully');
                this.loadData();
            });
        };

        this.insightUploader.onAfterAddingFile = (data: any) => {
            data.withCredentials = false;
            this.insightUploader.setOptions(this.getUploaderOptions(data.file.name, GovernancePdfType.Insight));
            this.insightUploader.uploadAll();
        };

        this.insightUploader.onSuccessItem = (item: any, response: any, status: any, headers: any) => {
            this.showInsightFile = false;
            let file = JSON.parse(response);
            this.insight.fileId = file.fileId;
            this.insight.fileName = file.filename;
            this.toasterService.pop('success', 'Success', 'Upload succeeded');
        };

        this.rootComponent.finishLoading();
    }

    private getUploaderOptions(name: string, type: GovernancePdfType): any {
        let auth = StorageService.get().authData;
        return {
            authToken: `Bearer ${auth.access_token}`,
            url: environment.serviceUrl + 'governanceserv/api/v1/filesclientplatform?companyId=' + this.companyId + '&governancePdfType=' + type,
            method: 'POST',
            headers: [
                { name: 'Content-Disposition', value: 'form-data; filename="' + name + '"' }
            ]
        }
    }

    private loadData() {
        forkJoin([
            this.governanceService.getGovernanceReport(this.companyId),
            this.governanceService.getGovernanceMetadata(this.companyId),
            this.governanceService.getGovernanceInsights(this.companyId)
        ]).subscribe(data => {
            this.report = data[0];
            this.metadata = data[1];
            if (data[2]['errorCode'] == 7000)
                this.hasProfile = false;
            else {
                this.profile = data[2];
                this.hasProfile = true;
                this.setInsights();
                this.count = this.profile.insights != null ? this.profile.insights.length : 0;
            }

            this.businessAndFinancialProfile = this.metadata.find(x => x.governancePdfType == GovernancePdfType.BusinessAndFinancialProfile);
            this.hasBusinessAndFinancialProfile = this.businessAndFinancialProfile != null && this.businessAndFinancialProfile.updateOperationType !== UpdateOperationType.Deleted;

            this.governanceDataProfile = this.metadata.find(x => x.governancePdfType == GovernancePdfType.GovernanceDataProfile);
            this.hasGovernanceDataProfile = this.governanceDataProfile != null && this.governanceDataProfile.updateOperationType !== UpdateOperationType.Deleted;
        });
    }

    public deleteReport(type: GovernancePdfType) {
        const swalOptions: SweetAlertOptions = Object.assign(UtilsService.getBaseSwalOptions(), {
            title: 'Delete Profile',
            text: 'Are you sure you want to delete this pdf profile?',
            confirmButtonClass: 'btn btn-primary',
            confirmButtonText: "Yes, I'm sure",
            imageUrl: '/assets/icons-svg/icon-warning.svg'
        });

        swal(swalOptions).then(result => {
            if (result && result.value) {
                this.governanceService.removeGovernanceReport(this.companyId, type).subscribe(_ => {
                    this.loadData();
                });
            }
        });
    }

    public openUploader(type: GovernancePdfType) {
        if (type == GovernancePdfType.BusinessAndFinancialProfile)
            this.selectedBusinessAndFinancial.nativeElement.click();
        else
            this.selectedGovernance.nativeElement.click()
    }

    public downloadPdf(type: GovernancePdfType) {
        let title = type == GovernancePdfType.BusinessAndFinancialProfile ? 'Business And Financial Profile' : 'Governance Data Profile';
        this.lrtmService.runTask(this.rootComponent, title + "_" + this.name + "_" + UtilsService.getReportDate(),
            LongRunningTaskTypeEnum.GovernancePDFS3,
            {
                CompanyId: this.companyId,
                GovernancePdfType: type
            }, true).subscribe(_ => { });
    }

    public onButtonClicked(event: any) {
        let insight = this.profile.insights.find(x => x.id == event.id);
        switch (event.operation) {
            case 'edit':
                this.showInsightFile = true;
                if(insight.publicationDate) insight.publicationDate = new Date(insight.publicationDate);
                this.insight = insight;
                this.insight.companyId = this.companyId;
                this.editModal.show();
                break;
            case 'delete':
                const swalOptions: SweetAlertOptions = Object.assign(UtilsService.getBaseSwalOptions(), {
                    title: 'Delete Insight',
                    text: 'Are you sure you want to delete the insight?',
                    confirmButtonClass: 'btn btn-primary',
                    confirmButtonText: "Yes, I'm sure",
                    imageUrl: '/assets/icons-svg/icon-warning.svg'
                });

                swal(swalOptions).then(result => {
                    if (result && result.value) {
                        this.governanceService.removeGovernanceInsights(this.companyId, insight.fileId).subscribe(_ => {
                            let index = this.profile.insights.findIndex(x => x.id == insight.id);
                            this.profile.insights.splice(index, 1);
                            this.insights.splice(index, 1);
                            this.insightsTable.updateSource(this.insights);
                        });
                    }
                });
                break;
            case 'download':
                //runTask
                this.lrtmService.runTask(this.rootComponent, insight.title + "_" + this.name + "_" + UtilsService.getReportDate(),
                    LongRunningTaskTypeEnum.GovernancePDFS3,
                    {
                        CompanyId: this.companyId,
                        FileId: insight.fileId,
                        GovernancePdfType: 2
                    }, true).subscribe(_ => { });
                break;
        }
    }

    public addInsight() {
        this.insight = {
            companyId: this.companyId,            
            publicationDate: new Date()
        };
        this.showInsightFile = false;
        this.editModal.show();
    }

    public saveInsight() {
        this.governanceService.setGovernanceInsights(this.insight).subscribe(data=>{
            this.profile = data;            
            this.setInsights();
            this.insightsTable.updateSource(this.insights);
            this.editModal.hide();
        });
    }

    private setInsights(){
        this.insights = this.profile.insights.map(insight => {
            return {
                publicationDate: new Date(insight.publicationDate),
                title: insight.title,
                createdBy: insight.createdBy,
                action: [
                    new TableButton('edit', { id: insight.id, operation: 'edit' }, true, ButtonType.Button),
                    new TableButton('delete', { id: insight.id, operation: 'delete' }, true, ButtonType.Button),
                    new TableButton('download', { id: insight.id, operation: 'download' }, true, ButtonType.Button)
                ]
            }
        });
    }
}